import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'

import Shelf from '@/views/shelf'
import Home from '@/views/shelf/home.vue'
import Classify from '@/views/shelf/classify.vue'
import Cart from '@/views/shelf/cart.vue'
import User from '@/views/shelf/user.vue'

const Login = () => import('@/views/login')
const Search = () => import('@/views/search')
const SearchList = () => import('@/views/search/list.vue')
const Detail = () => import('@/views/detail')
const Settlement = () => import('@/views/settlement')
const Orders = () => import('@/views/orders')

Vue.use(VueRouter)

const routes = [
  { path: '/login', component: Login },
  {
    path: '/',
    component: Shelf,
    redirect: '/home',
    children: [
      { path: '/home', component: Home },
      { path: '/classify', component: Classify },
      { path: '/cart', component: Cart },
      { path: '/user', component: User }
    ]
  },
  { path: '/search', component: Search },
  { path: '/searchlist', component: SearchList },
  { path: '/settlement', component: Settlement },
  { path: '/orders', component: Orders },
  { path: '/detail/:id', component: Detail }
]

const router = new VueRouter({
  routes
})

const whiteList = ['/orders', '/settlement']

router.beforeEach((to, from, next) => {
  if (whiteList.includes(to.path)) {
    if (store.getters.token) {
      next()
    } else {
      next('/login')
    }
  } else {
    next()
  }
})

export default router
